#!/bin/bash -e
#
# Forces a new ip on a DHCP device
LEASES_FILE=/var/lib/misc/dnsmasq.leases
mac_addr=$1
if [ -z "$mac_addr" ]; then
    echo "Usage: new_ip mac_addr"
    exit 1
fi

function get_next_ip() {
    cur_ip=$1
    prefix=$(echo $cur_ip | cut -d '.' -f 1,2)
    subnet=$(echo $cur_ip | cut -d '.' -f 3)
    new_subnet=$((($subnet + 1) % 256))
    postfix=$(echo $cur_ip | cut -d '.' -f 4)
    new_ip=$prefix.$new_subnet.$postfix
}

original=$(cat /etc/dnsmasq.conf | egrep "dhcp-host=$mac_addr,([0-9]{1,3}\.){3}[0-9]{1,3}" | head -1)
if [ -n "$original" ]; then
    original_ip=$(echo $original | cut -d ',' -f 2)
    get_next_ip $original_ip
    new="dhcp-host=$mac_addr,$new_ip"
    flock /etc/dnsmasq.conf sed -i s/$original/$new/ /etc/dnsmasq.conf
else
    # Get current ip from dnsmasq.leases
    original_ip=$(cat $LEASES_FILE | grep $mac_addr | cut -d ' ' -f 3)
    if [ -z "$original_ip" ]; then
        echo Could not find current ip for device: $mac_addr
        echo Current Leases:
        cat $LEASES_FILE
        exit 1
    fi
    get_next_ip $original_ip
    new="dhcp-host=$mac_addr,$new_ip"
    flock /etc/dnsmasq.conf echo $new >> /etc/dnsmasq.conf
fi
echo $mac_addr current IP: $original_ip new IP: $new_ip
